package com.freesky.biz.activity.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import com.aliyun.oss.internal.OSSUtils;
import com.freesky.biz.activity.domain.TSettlement;
import com.freesky.biz.activity.domain.TSettlementDetail;
import com.freesky.biz.activity.service.ISettlementService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.annotation.Log;
import com.freesky.common.core.controller.BaseController;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.core.domain.entity.SysUser;
import com.freesky.common.core.page.TableDataInfo;
import com.freesky.common.enums.BusinessType;
import com.freesky.common.utils.SecurityUtils;
import com.freesky.common.utils.StringUtils;
import com.freesky.common.utils.file.OssUtils;
import com.freesky.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static io.lettuce.core.pubsub.PubSubOutput.Type.message;

@RestController
@RequestMapping("/settlement")
public class SettlementController extends BaseController {

    @Autowired
    private ISettlementService settlementService;

    @Autowired
    private OssUtils ossUtils;

    @Value("${oss.host}")
    private String host;

    /**
     * 获取结算管理列表
     */
    @PreAuthorize("@ss.hasPermi('settlement:config:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSettlement entity) {
        startPage();
        List<TSettlement> list = settlementService.findList(entity);
        return getDataTable(list);
    }

    /**
     * 根据ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('settlement:config:query')")
    @GetMapping(value = "/{configId}")
    public AjaxResult getInfo(@PathVariable String configId) {
        TSettlement settlement = settlementService.get(configId);
        return success(settlement);
    }

    /**
     * 新增结算管理
     */
    @PreAuthorize("@ss.hasPermi('settlement:config:add')")
    @Log(title = "结算管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TSettlement entity) {
        entity.setSettleId(SeqUtil.getSeqId());
        entity.setCreateBy(String.valueOf(getUserId()));
        if(!settlementService.checkSettleNameUnique(entity)){
            return error("新增结算'" + entity.getSettleName() + "'失败，结算名称已存在");
        }
        return toAjax(settlementService.insert(entity));
    }

    /**
     * 修改结算管理
     */
    @PreAuthorize("@ss.hasPermi('settlement:config:edit')")
    @Log(title = "结算管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TSettlement entity) {
        entity.setUpdateBy(String.valueOf(getUserId()));
        if(!settlementService.checkSettleNameUnique(entity)){
            return error("修改结算'" + entity.getSettleName() + "'失败，结算名称已存在");
        }
        return toAjax(settlementService.update(entity));
    }


    /**
     * 删除结算管理
     */
    @PreAuthorize("@ss.hasPermi('settlement:config:remove')")
    @Log(title = "结算管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{configIds}")
    public AjaxResult remove(@PathVariable String[] configIds) {
        settlementService.deleteByIds(configIds);
        return success();
    }

    /**
     * 获取结算管理明细列表
     */
    @PreAuthorize("@ss.hasPermi('settlement:config:list')")
    @GetMapping("/selectDetailList")
    public TableDataInfo selectDetailList(TSettlementDetail entity) {
        startPage();
        List<TSettlementDetail> list = settlementService.findSettlementDetailList(entity);
        return getDataTable(list);
    }

//    @Log(title = "结算管理", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('settlement:config:import')")
//    @PostMapping("/importData")
//    public AjaxResult importData(MultipartFile file,
//                                 String settleId) throws Exception {
//        TSettlement settlement = settlementService.get(settleId);
//
//        if(settlement==null){
//            return AjaxResult.error("结算管理不存在，请核对!");
//        }
//
//        if("1".equalsIgnoreCase(settlement.getFlag())){
//            return AjaxResult.error("已上传过结算明细，无法重新上传!");
//        }
//
//        String createBy = String.valueOf(SecurityUtils.getLoginUser().getUserId());
//
//        Double totalAmt = 0.0;
//        List<TSettlementDetail> batchList = new ArrayList<>();
//
//        EasyExcel.read(file.getInputStream(), TSettlementDetail.class, new AnalysisEventListener<TSettlementDetail>() {
//            @Override
//            public void invoke(TSettlementDetail tSettlementDetail, AnalysisContext analysisContext) {
//                System.out.println("1111："+ JSON.toJSONString(tSettlementDetail));
//                if(tSettlementDetail.getSettleDetailId().indexOf("合计")>=0
//                        || tSettlementDetail.getSettleDetailId().indexOf("小计") >= 0){
//                    return;
//                }
//                totalAmt = totalAmt + Double.parseDouble(tSettlementDetail.getSettleMoney());
//                batchList.add(tSettlementDetail);
//            }
//
//            @Override
//            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//                System.out.println("doAfterAllAnalysed");
//            }
//        }).headRowNumber(3).sheet().doRead();
//
//        return AjaxResult.success();
//    }


    @Log(title = "结算管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('settlement:config:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,
                                 String settleId) throws Exception {
        TSettlement settlement = settlementService.get(settleId);

        if(settlement==null){
            return AjaxResult.error("结算管理不存在，请核对!");
        }

        if("1".equalsIgnoreCase(settlement.getFlag())){
            return AjaxResult.error("已上传过结算明细，无法重新上传!");
        }

        String createBy = String.valueOf(SecurityUtils.getLoginUser().getUserId());

        Double totalAmt = 0.0;

        ExcelUtil<TSettlementDetail> util = new ExcelUtil<TSettlementDetail>(TSettlementDetail.class);

        List<TSettlementDetail> settlementList = util.importExcel(file.getInputStream(),2);
        System.out.println(JSON.toJSONString(settlementList));

        if(settlementList==null || settlementList.size()<=0){
            return AjaxResult.error("导入结算数据不能为空！");
        }

        List<TSettlementDetail> batchList = new ArrayList<>();

        for(int i=0;i<settlementList.size();i++){

            TSettlementDetail settlementDetail = settlementList.get(i);
            logger.info(JSON.toJSONString(settlementDetail));

            String stockId = settlementDetail.getStockId().replaceAll(" ","");
            stockId = stockId.replaceAll("\u200B","");
            settlementDetail.setStockId(stockId);


            if((ObjectUtil.isNull(settlementDetail.getSettleMoney()))
                    || ObjectUtil.isNull(settlementDetail.getConsumeMoney())) {
                continue;
            }

            if(settlementDetail.getSettleDetailId().indexOf("合计")>=0
                        || settlementDetail.getSettleDetailId().indexOf("小计") >= 0){
                    continue;
            }

            if(ObjectUtil.isNull(settlementDetail.getRefundMoney())){
                settlementDetail.setRefundMoney(0.0);
            }

            totalAmt = totalAmt + settlementDetail.getSettleMoney();
            settlementDetail.setSettleId(settleId);
            settlementDetail.setSettleDetailId(SeqUtil.getSeqId());
            settlementDetail.setCreateBy(createBy);

            batchList.add(settlementDetail);

        }
        System.out.println("总金额："+totalAmt.longValue()+","+settlement.getSettleAmt().longValue());


        if(totalAmt.longValue() != settlement.getSettleAmt().longValue()){
            return AjaxResult.error("上传的结算金额与所填结算金额不一致！");
        }

        String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        Random rand = new Random();
        String filePrefix = DateUtil.format(new Date(),"yyyyMM")+ File.separator + DateUtil.format(new Date(),"ddHHmmss") +"_"+String.valueOf(rand.nextInt(9999));

        String fileKey = filePrefix + suffixName;
        ossUtils.uploadFileStream(fileKey,file.getInputStream());

        AjaxResult ajax = AjaxResult.success("上传成功!");
        ajax.put("fileUrl", host + "/"+ fileKey);
        ajax.put("originalFilename", file.getOriginalFilename());

        settlementService.batchAddSettlementDetail(batchList);

        settlementService.updateSettlementById(host + "/"+ fileKey,
                String.valueOf(SecurityUtils.getUserId()),settleId);

        return ajax;
    }
}
